package com.bw.smartpark

import android.os.CountDownTimer
import com.bw.common.mvvm.BaseViewActivity
import com.bw.smartpark.databinding.ActivitySanpinBinding
import com.bw.smartpark.view.DjsView
import com.tencent.mmkv.MMKV
import com.therouter.TheRouter

class SanpinActivity : BaseViewActivity<ActivitySanpinBinding>() {
    private var countdownView: DjsView? = null
    private var countDownTimer: CountDownTimer? = null
    private var hasNavigated = false // 防止多次跳转
    
    companion object {
        private var isAppStarted = false // 静态变量，防止应用重启
    }

    override fun initData() {
        // 如果应用已经启动过，直接跳转
        if (isAppStarted) {
            navigateToNextActivity()
            return
        }

        // 创建倒计时器
        countDownTimer = object : CountDownTimer(5000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                countdownView?.setRemainingTime(millisUntilFinished)
            }

            override fun onFinish() {
                countdownView?.setRemainingTime(0)
                if (!hasNavigated) {
                    navigateToNextActivity()
                }
            }
        }

        countDownTimer?.start() // 启动倒计时
        binding.tg.setOnClickListener {
            if (!hasNavigated) {
                navigateToNextActivity()
            }
        }
    }
    
    private fun navigateToNextActivity() {
        if (hasNavigated) return
        hasNavigated = true
        isAppStarted = true
        
        // 先取消倒计时器
        countDownTimer?.cancel()
        countDownTimer = null
        
        if (MMKV.defaultMMKV().decodeBool("isFirst", false)) {
            TheRouter.build("/mine/LoginActivity").navigation()
        } else {
            TheRouter.build("app/WelcomeActivity").navigation()
            MMKV.defaultMMKV().encode("isFirst", true)
        }
        finish()
    }

    override fun initView() {
        countdownView = binding.djs
        countdownView?.setTotalTime(5000) // 设置总时间5秒
    }

    override fun onPause() {
        super.onPause()
        // 暂停时取消倒计时器
        countDownTimer?.cancel()
    }

    override fun onResume() {
        super.onResume()
        // 如果还没有导航且倒计时器被取消了，重新启动
        if (!hasNavigated && countDownTimer == null && !isAppStarted) {
            countDownTimer = object : CountDownTimer(5000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    countdownView?.setRemainingTime(millisUntilFinished)
                }

                override fun onFinish() {
                    countdownView?.setRemainingTime(0)
                    if (!hasNavigated) {
                        navigateToNextActivity()
                    }
                }
            }
            countDownTimer?.start()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
        countDownTimer = null
        countdownView = null
    }
}